package com.lyd.management.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyd.management.common.R;
import com.lyd.management.mapper.UserMapper;
import com.lyd.management.pojo.Room;
import com.lyd.management.pojo.User;
import com.lyd.management.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserMapper usermapper;
    /**
     * 用户登录方法
     *
     * @param user user对象，包含用户名和密码
     * @return token
     */


    @SaIgnore
    @PostMapping("/login")
    public SaResult login(@RequestBody User user) {
        /*
        * 1. 前端将用户名和密码传给后端
        * 2. 后端根据用户名和密码获取要登陆的u对象
        * 3. 若u对象不为空，则：
        *  3.1 使用Sa-Token的login功能，储存token
        *  3.2 返回登录成功信息
        * */
        User u = userService.login(user.getUsername(), user.getPassword());
        if (u != null) {
            StpUtil.login(u.getId());
            System.out.println("当前用户权限："+StpUtil.getPermissionList());
            return SaResult.data(u);
        } else {
            return SaResult.error("用户名或密码错误");
        }
    }

    //用户登出
    @SaIgnore
    @PostMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("登出成功！");
    }

    //用户注册功能
    @SaIgnore
    @PostMapping("/register")
    public SaResult register(@RequestBody User user) {
        //数据库中新增成功，返回1
        boolean u = userService.register(user);

        if (u) {
            return SaResult.ok("注册成功");
        } else {
            return SaResult.error("注册失败");
        }

    }

    //修改用户

    @SaCheckRole("super-admin")
    @PostMapping("/modify")
    public SaResult modify(@RequestBody User user) {
        user.setUpdateUser(StpUtil.getLoginIdAsString());
        user.setUpdateTime(LocalDateTime.now());
        if (userService.updateById(user)) {
            return SaResult.ok("修改成功");
        } else {
            return SaResult.error("修改失败");
        }
    }




    //带分页的用户列表
    @SaIgnore
    @GetMapping("/page")
    public SaResult page(int page, int pageSize) {
        //构造分页构造器
        Page<User> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        queryWrapper.orderByDesc(User::getUpdateTime);
        //执行查询
        userService.page(pageInfo, queryWrapper);
        return SaResult.data(pageInfo);
    }


    //删除用户
    @SaCheckLogin
    @SaCheckRole("admin")
    @PostMapping("/delete")
    public SaResult deleteUser(@RequestBody JSONObject object){
        String id = object.getString("id");
        if(userService.removeById(id)){
            return SaResult.ok("删除成功");
        }else{
            return SaResult.error("删除失败");
        }
    }

    //修改密码
    @SaIgnore
    @PostMapping("/modifyPassword")
    public SaResult modifyPassword(@RequestBody Map<String, Object> map) {
        String operator = StpUtil.getLoginIdAsString();
        String target = (String) map.get("id");
        String oldPassword = (String) map.get("oldPassword");
        String newPassword = (String) map.get("newPassword");
        if (userService.modifyPassword(operator, target, oldPassword, newPassword)) {
            return SaResult.ok("修改成功，请重新登录！");
        } else {
            return SaResult.error("密码错误");
        }
    }

    @SaIgnore
    @GetMapping
    public SaResult getUserById(String id) {
        if (id == null) {
            id = StpUtil.getLoginIdAsString();
        }
        return SaResult.data(userService.getById(id));
    }

    @SaCheckLogin
    @SaCheckRole("admin")
    @PostMapping("/list")
    public SaResult list(@RequestBody User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //如果传入了人名，就返回该人名信息
        if(user.getUsername() != null && !user.getUsername().equals("")){
            queryWrapper.eq(User::getUsername,user.getUsername());
        }
        List<User> userList = userService.list(queryWrapper);
        return SaResult.data(userList);
    }




    @PostMapping("/role")
    public SaResult role(){
       User user1 = usermapper.selectById((Serializable)StpUtil.getLoginId());
       return SaResult.data(user1.getRole());
    }



}
